﻿using System;
using System.Web.UI;
using PropertyExpression.TypedDataBinding.Web.Example.Exapmle1.Model;
using PropertyExpression.TypedDataBinding.Web.WebControls;

namespace PropertyExpression.TypedDataBinding.Web.Example
{
    public partial class Example1Form : Page
    {
        protected readonly GroupBinder<A> aBinder = new GroupBinder<A>();
        private RepeaterBinder<B> bBinder;
        protected PairRepeaterBinder<C> cBinder = new PairRepeaterBinder<C>();

        protected void Page_Init(object sender, EventArgs e)
        {
            aBinder.Add(TextBox1).Add(x => x.Text, x => x.A001);
            aBinder.Add(TextBox2);

            bBinder = aBinder.Repeater(Repeater1, x => x.Bs);

            cBinder.RepeaterBinder.DataSource = () => bBinder.Data.Cs;

            aBinder.DataFunc = () => DataFactory.Instance.GetById<A>(1);

            aBinder.FromModel();
        }

        protected void Literal1_OnTypedInit(Literal sender)
        {
            bBinder.Add(sender).Add(x => x.Text, x => x.Id);
        }

        protected void Repeater1_OnTypedInit(Repeater sender)
        {
            bBinder.Add(sender, cBinder.RepeaterBinder);
        }

        protected void Literal2_OnTypedInit(HiddenField sender)
        {
            cBinder.AddForKey(sender).Add(x => x.Value, x => x.Id);
        }
            
        protected void TextBox4_OnTypedInit(TextBox sender)
        {
            cBinder.RepeaterBinder.Add(sender).Add(x => x.Text, x => x.BId);
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            aBinder.FromModel();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            aBinder.ToModel();
        }

        protected void TextBox2_TextChanged(object sender, EventArgs e)
        {
            cBinder.ToModel((Control)sender, dto => DataFactory.Instance.GetById<C>(
                                                dto.GetValue(x => x.Id)
                                                )
                );
        }

        protected void Literal3_OnTypedInit(Literal sender)
        {
            cBinder.AddForKey(sender).Add(x => x.Text, x => x.Id);
        }
    }
}